package com.seguriapp.administration.gwt.client;

import java.util.List;

import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.seguriapp.administration.gwt.client.activity.UsersListActivity;
import com.seguriapp.administration.gwt.client.activity.UsersListActivity.Display;
import com.seguriapp.common.gwt.client.celltable.HyperLinkColumn;
import com.seguriapp.common.gwt.client.celltable.SeguriAppCellTable;
import com.seguriapp.common.gwt.client.pagination.SearchPagination;
import com.seguriapp.entities.User;

public class UsersListPage extends Composite implements Display {

  private static UsersListPageUiBinder uiBinder = GWT.create(UsersListPageUiBinder.class);

  interface UsersListPageUiBinder extends UiBinder<Widget, UsersListPage> {
  }

  @UiField
  protected HTMLPanel usersGridPanel;
  @UiField
  protected InlineLabel noDataLabel;
  @UiField
  protected SearchPagination pagination;

  private UsersListActivity presenter;

  private CellTable<User> usersGrid;
  private TextColumn<User> usernameColumn;
  private TextColumn<User> administratorColumn;
  private TextColumn<User> lastDateLoggedInColumn;
  private Column<User, String> editDetailColumn;

  public UsersListPage() {
    initWidget(uiBinder.createAndBindUi(this));
    initializeColumns();
    initializeDataGrid();
    initializeHandlers();
  }

  public void setPresenter(final UsersListActivity presenter) {
    this.presenter = presenter;
  }

  private void initializeColumns() {
    usernameColumn = new TextColumn<User>() {

      @Override
      public String getValue(final User user) {
        return user.getUsername();
      }
    };

    administratorColumn = new TextColumn<User>() {

      @Override
      public String getValue(final User user) {
        if (user.isAdministrator()) {
          return "Y";
        } else {
          return "N";
        }
      }
    };

    lastDateLoggedInColumn = new TextColumn<User>() {

      @Override
      public String getValue(final User user) {
        final DateTimeFormat DATE_FORMAT = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm:ss");
        return DATE_FORMAT.format(user.getLastDateLoggedIn());
      }
    };

    editDetailColumn = new HyperLinkColumn<User>() {

      @Override
      public String getValue(final User user) {
        return "";
      }

      @Override
      public void render(final Context context, final User user, final SafeHtmlBuilder sb) {
        setTooltip("Ver Detalle");
        setStyle("detailsIcon");
        super.render(context, user, sb);
      }

    };

    usernameColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
    administratorColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
    lastDateLoggedInColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
    editDetailColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

    usernameColumn.setSortable(true);
    administratorColumn.setSortable(true);
    lastDateLoggedInColumn.setSortable(true);

    editDetailColumn.setFieldUpdater(new FieldUpdater<User, String>() {

      public void update(final int index, final User user, final String value) {
        presenter.goToEditUserPage(user);
      }
    });

  }

  private void initializeHandlers() {
    AsyncDataProvider<User> dataProvider = new AsyncDataProvider<User>() {

      @Override
      protected void onRangeChanged(HasData<User> display) {

        // Get the ColumnSortInfo from the table.
        final ColumnSortList sortList = usersGrid.getColumnSortList();
        if (sortList.size() > 0) {
          presenter.setAscending(sortList.get(0).isAscending());
          if (sortList.get(0).getColumn().equals(usernameColumn)) {
            presenter.setColumnSort("username");
          } else if (sortList.get(0).getColumn().equals(administratorColumn)) {
            presenter.setColumnSort("administrator");
          } else if (sortList.get(0).getColumn().equals(lastDateLoggedInColumn)) {
            presenter.setColumnSort("lastDateLoggedIn");
          }
          presenter.updateUsersList();
        }
      }
    };

    dataProvider.addDataDisplay(usersGrid);

    // Add a ColumnSortEvent.AsyncHandler to connect sorting to the
    // AsyncDataPRrovider.
    AsyncHandler columnSortHandler = new AsyncHandler(usersGrid);
    usersGrid.addColumnSortHandler(columnSortHandler);

  }

  private void generateTable() {
    usersGrid = new SeguriAppCellTable<User>();
    usersGrid.addColumn(usernameColumn, SafeHtmlUtils.fromTrustedString("Usuario"));
    usersGrid.addColumn(administratorColumn, SafeHtmlUtils.fromTrustedString("Es Admin"));
    usersGrid.addColumn(lastDateLoggedInColumn, SafeHtmlUtils.fromTrustedString("&Uacute;ltima fecha de inicio de sesi&oacute;n"));
    usersGrid.addColumn(editDetailColumn, SafeHtmlUtils.fromTrustedString("Editar"));
    usersGrid.setColumnWidth(usernameColumn, "30%");
    usersGrid.setColumnWidth(administratorColumn, "30%");
    usersGrid.setColumnWidth(lastDateLoggedInColumn, "20%");
    usersGrid.setColumnWidth(editDetailColumn, "20%");
  }

  private void initializeDataGrid() {
    generateTable();
    usersGridPanel.clear();
    usersGridPanel.add(usersGrid);
  }

  public void setGridData(final List<User> usersList) {
    noDataLabel.setVisible(false);
    usersGridPanel.setVisible(true);
    usersGrid.setRowData(0, usersList);
    usersGrid.setRowCount(usersList.size(), true);
  }

  public void setPagination(final long currentPage, final long totalPages, final long maxPages) {
    pagination.setPagination(currentPage, totalPages, maxPages);
  }

  public void showNoDataMessage() {
    noDataLabel.setVisible(true);
    usersGridPanel.setVisible(false);
  }

  public SearchPagination getPagination() {
    return pagination;
  }

  @UiHandler("createUser")
  protected void onCreateUserClick(final ClickEvent event) {
    presenter.goToEditUserPage(null);
  }

}
